package com.example.servlet;

import com.example.dao.UserDao;
import com.example.domain.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/UserUpdateInfoServlet")
public class UserUpdateInfoServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
       User user = (User)request.getSession().getAttribute("user");
       String username = request.getParameter("username");
       String password = request.getParameter("password");
       String confirmPassword = request.getParameter("confirmPassword");
       String email = request.getParameter("email");
       user.setUsername(username);

       if ((!user.getUsername().equals(username)) && userDao.checkUsername(username)){
           request.setAttribute("msg","用户名已存在,修改失败！");
           request.getRequestDispatcher("updateUserInfo.jsp").forward(request,response);
           return;
       }
       if ((!user.getEmail().equals(email)) && userDao.checkEmail(user.getEmail())){
           request.setAttribute("msg","邮箱已存在,修改失败！");
           request.getRequestDispatcher("updateUserInfo.jsp").forward(request,response);
           return;
       }
       if(confirmPassword.equals("")){
           user.setPassword(password);
       }else{
           if(confirmPassword.equals(password)){
               user.setPassword(password);
           }else{
               request.setAttribute("msg","两次密码不一致");
               request.getRequestDispatcher("updateUserInfo.jsp").forward(request,response);
               return;
           }
       }
       user.setEmail(email);
//       int flag = Integer.parseInt(request.getParameter("isAdmin"));
//       if(flag==1){
//           user.setIsAdmin(true);
//       }else{
//           user.setIsAdmin(false);
//       }
       int affectedRows = userDao.updateUserInfo(user);
       if(affectedRows>0){
           request.setAttribute("msg", "修改成功！");
           request.getRequestDispatcher("updateUserInfo.jsp").forward(request,response);
       }else {
           request.setAttribute("msg", "修改失败!");
           request.getRequestDispatcher("updateUserInfo.jsp").forward(request, response);
       }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
